package risk.control.application.utils;

import com.alibaba.fastjson2.JSON;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.HashMap;
import java.util.Random;

/**
 * 设备id工具类
 */
public class EquipmentIdUtils {

    // 定义所有可能的字符
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 生成设备唯一id
     *
     * @return EquipmentId
     */
    public static String generateEquipmentId() {
        String seed1 = UUIDUtils.generate();//uuid
        String seed2 = String.valueOf(System.currentTimeMillis());
        String seed3 = getsSed();
        String seed4 = getsSed();
        String seed5 = getsSed();
        //按一定的顺序1-3-1-4-2-5->全部小写再md5
        String s = seed1.toLowerCase() //
                + seed3.toLowerCase() //
                + seed1.toLowerCase()//
                + seed4.toLowerCase() //
                + seed2.toLowerCase() //
                + seed5.toLowerCase(); //
        String dynamicSignature = DigestUtils.md5Hex(s);

        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("seed1", seed1);
        paramsMap.put("seed2", seed2);
        paramsMap.put("seed3", seed3);
        paramsMap.put("seed4", seed4);
        paramsMap.put("seed5", seed5);
        paramsMap.put("signature", dynamicSignature);
        return JSON.toJSONString(paramsMap);//map->json字符串
    }

    //随机获取4个元素->组成字符串
    private static String getsSed() {
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < 4; j++) {
            // 随机选取一个字符
            Random random = new Random();
            int index = random.nextInt(CHARS.length());
            sb.append(CHARS.charAt(index));
        }
        return sb.toString();
    }

}
